<?php
class Db{
	public $conn;
	public function __construct($host, $username, $password, $dataname){
		$this->conn = mysqli_connect($host, $username, $password, $dataname);
		if(!$this->conn){
			exit('connect data error!');
		}

		mysqli_query($this->conn, "SET NAMES UTF-8");
	}

	//增删改查
	public function insert($table, $bind=array()){
	    $set = array();
	    foreach ($bind as $col => $val) {
	        $set[] = "`$col`";
	        $vals[] = "'$val'";
	    }
	   $sql = "INSERT INTO "
             . $table
             . ' (' . implode(', ', $set).') '
             . 'VALUES (' . implode(', ', $vals).')';
        mysqli_query($this->conn, $sql);
        return mysqli_insert_id($this->conn);
	}

	public function update($table, $bind=array(),$where = ''){
	    $set = array();
	    foreach ($bind as $col => $val) {
	        $set[] = "$col = '$val'";
	        unset($set[$col]);
	    }
	    $sql = "UPDATE "
             . $table
             . ' SET ' . implode(',', $set)
             . (($where) ? " WHERE $where" : '');

        return mysqli_query($this->conn, $sql);
	}

	public function getOneRecord($sql){
		$result = mysqli_query($this->conn, $sql);
		$assoc_result = mysqli_fetch_array($result, MYSQLI_ASSOC);

		return $assoc_result;
	}

	public function getMultiRecords($sql){
		$aRet = [];
		$result = mysqli_query($this->conn, $sql);
		while($assoc_result = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			$aRet[] = $assoc_result;
		}

		return $aRet;
	}

	public function dbClose(){
		mysqli_close($this->conn);
	}
}